package com.lft.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lft.common.utils.PageUtils;
import com.lft.common.utils.Query;
import com.lft.gulimall.product.dao.CategoryDao;
import com.lft.gulimall.product.entity.CategoryEntity;
import com.lft.gulimall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Laifengting
 */
@Service ("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
	
	// @Autowired
	// CategoryDao categoryDao;
	
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<CategoryEntity> page = this.page(
				new Query<CategoryEntity>().getPage(params),
				new QueryWrapper<>()
		);
		
		return new PageUtils(page);
	}
	
	@Override
	public List<CategoryEntity> listWithTree() {
		// 1. 查出所有分类
		List<CategoryEntity> entities = baseMapper
				.selectList(null);
		return entities
				// 2. 组装成父子的树形结构
				// 2.1 找到所有的一级分类
				.stream()
				// 过滤
				.filter(categoryEntity -> categoryEntity.getParentCid() == 0)
				// 重新映射子菜单
				.peek(menu -> menu.setChildren(getChildren(menu, entities)))
				// .map(menu -> {
				// 	menu.setChildren(getChildren(menu, entities));
				// 	return menu;
				// })
				// 排序
				// .sorted((menu1, menu2) -> {
				// 	return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort
				// 	());
				// })
				.sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
				// 收集成集合
				.collect(Collectors.toList());
	}
	
	private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
		return all
				.stream()
				// 过滤
				.filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
				// 重新映射子菜单
				.peek(menu -> menu.setChildren(getChildren(menu, all)))
				// 排序
				.sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
				// 收集成集合
				.collect(Collectors.toList());
	}
	
	@Override
	public void removeMenuByIds(List<Long> asList) {
		// TODO 1. 检查当前删除的菜单，是否被别的地方引用。
		baseMapper.deleteBatchIds(asList);
	}
	
}